#!/usr/bin/env bash
#
# Summary: Set or show the local application-specific PHP version
#
# Usage: phpenv local <version>
#        phpenv local --unset
#
# Sets the local application-specific PHP version by writing the
# version name to a file named `.php-version'.
#
# When you run a PHP command, phpenv will look for a `.php-version'
# file in the current directory and each parent directory. If no such
# file is found in the tree, phpenv will use the global PHP version
# specified with `phpenv global'. A version specified with the
# `PHPENV_VERSION' environment variable takes precedence over local
# and global versions.
#
# For backwards compatibility, phpenv will also read version
# specifications from `.phpenv-version' files, but a `.php-version'
# file in the same directory takes precedence.
#
# <version> should be a string matching a PHP version known to phpenv.
# The special version string `system' will use your default system PHP.
# Run `phpenv versions' for a list of available PHP versions.

set -e
[ -n "$PHPENV_DEBUG" ] && set -x

# Provide phpenv completions
if [ "$1" = "--complete" ]; then
  echo --unset
  echo system
  exec phpenv-versions --bare
fi

PHPENV_VERSION="$1"

if [ "$PHPENV_VERSION" = "--unset" ]; then
  rm -f .php-version .phpenv-version
  PHPENV_VERSION=""
elif [ -n "$PHPENV_VERSION" ]; then
  if [ "$(PHPENV_VERSION= phpenv-version-origin)" -ef .phpenv-version ]; then
    rm -f .phpenv-version
    { echo "phpenv: removed existing \`.phpenv-version' file and migrated"
      echo "       local version specification to \`.php-version' file"
    } >&2
  fi
  phpenv-version-file-write .php-version "$PHPENV_VERSION"
  echo "$PHPENV_VERSION" >&2
fi
if [ -z "$PHPENV_VERSION" ]; then
  phpenv-version-file-read .php-version ||
  phpenv-version-file-read .phpenv-version ||
  { echo "phpenv: no local version configured for this directory"
    exit 1
  } >&2
fi
